package org.wutopia.labcloud.domain.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.wutopia.labcloud.domain.product.controller.vo.input.ProductCreateAdInputVO;
import org.wutopia.labcloud.domain.product.controller.vo.output.ProductGetAdvertisingOutputVO;
import org.wutopia.labcloud.domain.product.dao.ProductAdvertisingBoardDao;
import org.wutopia.labcloud.domain.product.dao.entity.mysql.ProductAdvertisingBoard;
import org.wutopia.labcloud.domain.product.service.ProductAdvertisingService;
import org.wutopia.labcloud.service.api.service.dubbo.FileService;

import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class ProductAdvertisingServiceImpl implements ProductAdvertisingService {

    private ProductAdvertisingBoardDao productAdvertisingBoardDao;

    @DubboReference
    private FileService fileService;

    @Override
    public List<ProductGetAdvertisingOutputVO> getAdvertising() throws Exception {

        QueryWrapper<ProductAdvertisingBoard> q = new QueryWrapper<>();


        List<ProductAdvertisingBoard> productAdvertisingBoards = productAdvertisingBoardDao.selectList(q);

        List<ProductGetAdvertisingOutputVO> collect = new ArrayList<>();
        for (ProductAdvertisingBoard productAdvertisingBoard : productAdvertisingBoards) {
            ProductGetAdvertisingOutputVO output = new ProductGetAdvertisingOutputVO();
            output.setId(productAdvertisingBoard.getId());
            output.setProductId(productAdvertisingBoard.getProductId());
            String coverAddr = productAdvertisingBoard.getCoverAddr();
            if (coverAddr == null) {
                throw new Exception("图片为空");
            }
            String[] split = coverAddr.split(":");
            String fileUrl = fileService.getFileUrl(split[0], split[1]);
            output.setCoverAddr(fileUrl);
            collect.add(output);
        }

        return collect;
    }

    @Override
    public void createAd(ProductCreateAdInputVO vo) {

        ProductAdvertisingBoard entity = new ProductAdvertisingBoard();

        entity.setProductId(vo.getProductId());
        entity.setCoverAddr(vo.getCoverAddr());

        productAdvertisingBoardDao.insert(entity);

    }

    @Override
    public void deleteAd(Long id) {
        productAdvertisingBoardDao.deleteById(id);
    }
}
